package aod.android.com.bernay.live.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.google.gson.Gson;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import aod.android.com.bernay.R;
import aod.android.com.bernay.base.BernayBaseActivity;
import aod.android.com.bernay.fixing.activity.FixingAddActivity;
import aod.android.com.bernay.fixing.activity.FixingAddNameActivity;
import aod.android.com.bernay.http.BernayApi;
import aod.android.com.bernay.http.BernayCallback;
import aod.android.com.bernay.live.adapter.FullyGridLayoutManager;
import aod.android.com.bernay.live.adapter.GridImageAdapter;
import aod.android.com.bernay.live.until.ImageUpdata;
import aod.android.com.bernay.live.view.PhotoPopupWindow;
import aod.android.com.bernay.loginandregister.bean.UserDataBean;
import aod.android.com.bernay.util.ImageUtils;
import aod.android.com.bernay.util.SharePreUtils;
import chen.lion.hilib.util.LogUtils;
import chen.lion.hilib.view.bind.HiView;

import static chen.lion.hilib.HiApp.photo;

public class AddLiveActivity extends BernayBaseActivity {
    @HiView(R.id.live_ed_name)
    EditText live_ed_name;
    @HiView(R.id.live_ed_content)
    EditText live_ed_content;
    @HiView(R.id.recyclerView)
    RecyclerView recyclerView;
    @HiView(R.id.add_live_lay)
    LinearLayout add_live_lay;
    private String liveNameStr;
    private String liveConentStr;
    private GridImageAdapter adapter = null;//适配器
    private List<LocalMedia> selectList = new ArrayList<>();//选择图片数组
    private int maxSelectNum = 3;//图片选择数量
    private int maxSelectVideoNum = 1;//视频选择数量
    private PhotoPopupWindow popupWindow;//照片弹出框
    private String selectType = "";//空为未选择，1为选择照片，2为选择视频
    private int themeId;
    private List<String> qiNiuImageList = null;//上传七牛文件地址
    private ImageUpdata imageUpdata = null;
    private StringBuffer backImageName = new StringBuffer();//七牛返回的图片文件名称
    private StringBuffer backVideoName = new StringBuffer();//七牛返回的视频文件名称
    private String sourceStr = "";
    @Override
    protected int initLayout() {
        return R.layout.activity_addlive;
    }

    @Override
    protected void initData() {
        themeId = R.style.picture_default_style;//选择图片框样式
        FullyGridLayoutManager manager = new FullyGridLayoutManager(AddLiveActivity.this, 4, GridLayoutManager.VERTICAL, false);
        recyclerView.setLayoutManager(manager);

        adapter = new GridImageAdapter(AddLiveActivity.this, onAddPicClickListener);
        adapter.setList(selectList);
        adapter.setSelectMax(maxSelectNum);
        recyclerView.setAdapter(adapter);

        adapter.setOnItemClickListener(new GridImageAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position, View v) {
                if (selectList.size() > 0) {
                    LocalMedia media = selectList.get(position);
                    String pictureType = media.getPictureType();
                    int mediaType = PictureMimeType.pictureToVideo(pictureType);
                    switch (mediaType) {
                        case 1:
                            // 预览图片 可自定长按保存路径
                            //PictureSelector.create(MainActivity.this).themeStyle(themeId).externalPicturePreview(position, "/custom_file", selectList);
                            PictureSelector.create(AddLiveActivity.this).themeStyle(themeId).openExternalPreview(position, selectList);
                            break;
                        case 2:
                            // 预览视频
                            PictureSelector.create(AddLiveActivity.this).externalPictureVideo(media.getPath());
                            break;
                    }
                }
            }
            @Override
            public void deleteFile(int i) {
                //当图片或者视频被删除完以后 重置图片和视频的弹出框
                if (i == 0) {
                    selectType = "";
                }
            }
        });



        initTitle(getString(R.string.add_live_title_name), getString(R.string.issue_live), new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                liveNameStr = live_ed_name.getText().toString();
                liveConentStr = live_ed_content.getText().toString();
                if (TextUtils.isEmpty(liveNameStr)) {
                    showError("请输入直播名称");
                    return;
                }
                if (TextUtils.isEmpty(liveConentStr)) {
                    showError("请输入直播内容");
                    return;
                }
                if(selectType.equals("")){
                    showError("请选择上传的图片或者视频");
                    return;
                }

                uploadLive();
            }
        });
    }

    private void uploadLive() {


        qiNiuImageList = new ArrayList<>();
        for (LocalMedia media : selectList) {
            String path = "";
            if (selectType.equals("1")) {
                //判断压缩地址是否为空，图片可以压缩，视频暂时不能压缩
                path = media.getPath();
            } else if(selectType.equals("2")){
                path = media.getPath();
            }
            qiNiuImageList.add(path);
        }
        imageUpdata = new ImageUpdata(AddLiveActivity.this, selectType, qiNiuImageList, new ImageUpdata.BackFileNameListener() {
            @Override
            public void onBackFileName(List<String> backFileNames) {
                for (String s : backFileNames) {
                    if (selectType.equals("1")) {
                        backImageName.append(s + ",");//上传图片

                    } else if (selectType.equals("2")) {
                        backVideoName.append(s);//上传视频
                    }
                }
                if(selectType.equals("1")){
                   sourceStr =  backImageName.toString();
                }else if(selectType.equals("2")) {
                    sourceStr =   backVideoName.toString();
                }
                BernayApi.http().uploadlive(SharePreUtils.newInstance(AddLiveActivity.this).getUserId(),
                        SharePreUtils.newInstance(AddLiveActivity.this).getToken(), liveNameStr, liveConentStr, sourceStr, selectType, new BernayCallback() {
                            @Override
                            public void onJsonData(String json) {
                                Gson gson = new Gson();
                                UserDataBean userDataBean = gson.fromJson(json, UserDataBean.class);
                                if (userDataBean.getStatus() == 1) {
                                    showToast("上传直播成功");
                                    finish();
                                } else {
                                    showToast("上传直播失败");
                                }
                            }

                            @Override
                            public void onHttpFailure(IOException e) {
                                showToast("上传直播失败");
                            }
                        });

            }
        });




    }

    private GridImageAdapter.onAddPicClickListener onAddPicClickListener = new GridImageAdapter.onAddPicClickListener() {
        @Override
        public void onAddPicClick() {
            if (selectList.size() == 0) {
                selectType = "";
            }
            popupWindow = new PhotoPopupWindow(AddLiveActivity.this, selectType);
            popupWindow.setOnItemClickListener(new PhotoPopupWindow.OnItemClickListener() {
                @Override
                public void onItemPhotoClick(int positon) {
                    //拍照
                    selectType = "1";
                    handler.sendEmptyMessage(0);
                }

                @Override
                public void onItemVideoClick(int positon) {
                    //录视频
                    selectType = "2";
                    handler.sendEmptyMessage(1);
                }
            });

            popupWindow.showAtLocation(add_live_lay, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
        }
    };
    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0: //拍照
                    photo();
                    popupWindow.dismiss();
                    break;
                case 1: //录视频
                    video();
                    popupWindow.dismiss();
                    break;
            }
        }
    };

    private void video() {
        PictureSelector.create(AddLiveActivity.this).openGallery(PictureMimeType.ofVideo())// 单独拍视频，也可录像或也可音频 看你传入的类型是图片or视频
                .theme(themeId)// 主题样式设置 具体参考 values/styles   用法：R.style.picture.white.style
                .maxSelectNum(maxSelectVideoNum)// 最大图片选择数量
                .minSelectNum(maxSelectVideoNum)// 最小选择数量
//                .imageSpanCount(4)// 每行显示个数
                .selectionMode(PictureConfig.MULTIPLE)// 多选 or 单选 PictureConfig.MULTIPLE : PictureConfig.SINGLE
//                    .previewImage(true)// 是否可预览图片
                .previewVideo(true)// 是否可预览视频
//                    .enablePreviewAudio(true) // 是否可播放音频
//                    .isCamera(true)// 是否显示拍照按钮
//                    .isZoomAnim(true)// 图片列表点击 缩放效果 默认true
//                    .imageFormat(PictureMimeType.PNG)// 拍照保存图片格式后缀,默认jpeg
                //.setOutputCameraPath("/CustomPath")// 自定义拍照保存路径
//                    .enableCrop(false)// 是否裁剪
                .compress(true)// 是否压缩
                .synOrAsy(false)//同步true或异步false 压缩 默认同步
//                .compressSavePath(getPath())//压缩图片保存地址
                //.sizeMultiplier(0.5f)// glide 加载图片大小 0~1之间 如设置 .glideOverride()无效
//                    .glideOverride(160, 160)// glide 加载宽高，越小图片列表越流畅，但会影响列表图片浏览的清晰度
                .withAspectRatio(3, 4)// 裁剪比例 如16:9 3:2 3:4 1:1 可自定义
//                    .hideBottomControls(true)// 是否显示uCrop工具栏，默认不显示 false : true
//                .isGif(false)// 是否显示gif图片
//                .freeStyleCropEnabled(false)// 裁剪框是否可拖拽
//                .circleDimmedLayer(false)// 是否圆形裁剪
//                .showCropFrame(false)// 是否显示裁剪矩形边框 圆形裁剪时建议设为false
//                .showCropGrid(false)// 是否显示裁剪矩形网格 圆形裁剪时建议设为false
//                .openClickSound(true)// 是否开启点击声音
                .selectionMedia(selectList)// 是否传入已选图片
                //.isDragFrame(false)// 是否可拖动裁剪框(固定)
                .videoMaxSecond(31)//显示多少秒以内的视频or音频也可适用
//                        .videoMinSecond(30)
                //.previewEggs(false)// 预览图片时 是否增强左右滑动图片体验(图片滑动一半即可看到上一张是否选中)
                .cropCompressQuality(30)// 裁剪压缩质量 默认100
                .minimumCompressSize(100)// 小于100kb的图片不压缩
                //.cropWH()// 裁剪宽高比，设置如果大于图片本身宽高则无效
                //.rotateEnabled(true) // 裁剪是否可旋转图片
                //.scaleEnabled(true)// 裁剪是否可放大缩小图片
                .videoQuality(0)// 视频录制质量 0 or 1
                .recordVideoSecond(30)//录制视频秒数 默认60s
                .forResult(PictureConfig.CHOOSE_REQUEST);//结果回调onActivityResult code
    }

    private void photo() {
        PictureSelector.create(AddLiveActivity.this).openGallery(PictureMimeType.ofImage())// 全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()
                .theme(themeId)// 主题样式设置 具体参考 values/styles   用法：R.style.picture.white.style
                .maxSelectNum(maxSelectNum)// 最大图片选择数量
                .minSelectNum(1)// 最小选择数量
                .imageSpanCount(3)// 每行显示个数
                .selectionMode(PictureConfig.MULTIPLE)// 多选 or 单选 PictureConfig.MULTIPLE : PictureConfig.SINGLE
                .previewImage(true)// 是否可预览图片
                .enablePreviewAudio(true) // 是否可播放音频
                .isCamera(true)// 是否显示拍照按钮
                .isZoomAnim(true)// 图片列表点击 缩放效果 默认true
                .imageFormat(PictureMimeType.PNG)// 拍照保存图片格式后缀,默认jpeg
                .enableCrop(false)// 是否裁剪
                .compress(true)// 是否压缩
                .synOrAsy(false)//同步true或异步false 压缩 默认同步
                .glideOverride(160, 160)// glide 加载宽高，越小图片列表越流畅，但会影响列表图片浏览的清晰度
                .withAspectRatio(3, 4)// 裁剪比例 如16:9 3:2 3:4 1:1 可自定义
                .hideBottomControls(true)// 是否显示uCrop工具栏，默认不显示 false : tru
                .selectionMedia(selectList)// 是否传入已选图片
                .videoMaxSecond(15).videoMinSecond(10)
                .cropCompressQuality(80)// 裁剪压缩质量 默认100
                .minimumCompressSize(100)// 小于100kb的图片不压缩
                .forResult(PictureConfig.CHOOSE_REQUEST);//结果回调onActivityResult code
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    // 图片选择结果回调
                    selectList = PictureSelector.obtainMultipleResult(data);
                    // 例如 LocalMedia 里面返回三种path
                    // 1.media.getPath(); 为原图path
                    // 2.media.getCutPath();为裁剪后path，需判断media.isCut();是否为true
                    // 3.media.getCompressPath();为压缩后path，需判断media.isCompressed();是否为true
                    // 如果裁剪并压缩了，已取压缩路径为准，因为是先裁剪后压缩的
//                    for (LocalMedia media : selectList) {
//                        Log.i("选择回调回来的压缩地址-----》", media.getCompressPath());
//                    }
                    adapter.setList(selectList);
                    adapter.notifyDataSetChanged();
                    break;
            }
        }
    }
}
